using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using MauiBuilder.Services;

namespace MauiBuilder.ViewModels
{
    /// <summary>
    /// 注册页面的视图模型，处理用户注册相关的业务逻辑
    /// </summary>
    public partial class RegisterViewModel : BaseViewModel
    {
        /// <summary>
        /// 用户名
        /// </summary>
        [ObservableProperty]
        private string username = string.Empty;

        /// <summary>
        /// 密码
        /// </summary>
        [ObservableProperty]
        private string password = string.Empty;

        /// <summary>
        /// 确认密码
        /// </summary>
        [ObservableProperty]
        private string confirmPassword = string.Empty;

        /// <summary>
        /// 是否正在加载中
        /// </summary>
        [ObservableProperty]
        private bool isLoading;

        /// <summary>
        /// 注册命令，处理用户注册逻辑
        /// </summary>
        [RelayCommand]
        private async Task OnRegister()
        {
            LogManager.Instance.LogInfo($"尝试注册新用户，用户名: {Username}");
            
            if (string.IsNullOrWhiteSpace(Username) || string.IsNullOrWhiteSpace(Password) || string.IsNullOrWhiteSpace(ConfirmPassword))
            {
                LogManager.Instance.LogWarning("注册失败：信息不完整");
                await AppShell.DisplayToastAsync("请填写完整信息");
                return;
            }

            if (Password != ConfirmPassword)
            {
                LogManager.Instance.LogWarning("注册失败：两次密码不一致");
                await AppShell.DisplayToastAsync("两次输入的密码不一致");
                return;
            }

            IsLoading = true;
            LogManager.Instance.LogInfo("开始注册流程");
            
            try
            {
                // 模拟注册过程
                await Task.Delay(1000);
                
                // 实际项目中应该调用API进行注册
                LogManager.Instance.LogInfo($"用户 {Username} 注册成功");
                await AppShell.DisplayToastAsync("注册成功");
                // 注册成功后返回登录页面
                await Shell.Current.GoToAsync("..");
            }
            catch (Exception ex)
            {
                LogManager.Instance.LogError("注册过程中发生异常", ex);
                await AppShell.DisplayToastAsync("注册失败，请稍后重试");
            }
            finally
            {
                IsLoading = false;
            }
        }

        /// <summary>
        /// 跳转到登录页面的命令
        /// </summary>
        [RelayCommand]
        private async Task OnGoToLogin()
        {
            LogManager.Instance.LogInfo("用户请求返回登录页面");
            await Shell.Current.GoToAsync("..");
        }
    }
}